const Joi = require('joi');
const { User } = require('../models');
const { 
  successResponse, 
  errorResponse, 
  paginatedResponse,
  generateInviteCode,
  generateToken
} = require('../utils/helpers');
const { validateData, commonSchemas } = require('../utils/validation');

/**
 * 用户管理控制器
 */
class UserController {
  /**
   * 获取当前租户的所有用户
   */
  async getUsers(request, reply) {
    try {
      const { tenantId } = request.tenant;
      const { 
        page = 1, 
        limit = 10, 
        sort = 'desc', 
        sortBy = 'createdAt',
        search,
        role,
        status
      } = request.query;

      // 构建查询条件
      const query = { tenantId };
      
      if (search) {
        query.$or = [
          { firstName: { $regex: search, $options: 'i' } },
          { lastName: { $regex: search, $options: 'i' } },
          { email: { $regex: search, $options: 'i' } }
        ];
      }
      
      if (role) {
        query.role = role;
      }
      
      if (status) {
        query.status = status;
      }

      // 计算分页
      const skip = (page - 1) * limit;
      const sortOrder = sort === 'asc' ? 1 : -1;

      // 查询用户
      const [users, total] = await Promise.all([
        User.find(query)
          .select('-password -resetPasswordToken -emailVerificationToken')
          .sort({ [sortBy]: sortOrder })
          .skip(skip)
          .limit(limit)
          .lean(),
        User.countDocuments(query)
      ]);

      return reply.send(paginatedResponse(users, total, page, limit, 'Users retrieved successfully'));
    } catch (error) {
      request.log.error('Error getting users:', error);
      return reply.code(500).send(errorResponse('Failed to get users', { message: error.message }));
    }
  }

  /**
   * 根据ID获取用户
   */
  async getUserById(request, reply) {
    try {
      const { userId } = request.params;
      const { tenantId } = request.tenant;

      const user = await User.findOne({ 
        _id: userId, 
        tenantId 
      }).select('-password -resetPasswordToken -emailVerificationToken').lean();

      if (!user) {
        return reply.code(404).send(errorResponse('User not found'));
      }

      return reply.send(successResponse(user, 'User retrieved successfully'));
    } catch (error) {
      request.log.error('Error getting user:', error);
      return reply.code(500).send(errorResponse('Failed to get user', { message: error.message }));
    }
  }

  /**
   * 更新用户信息
   */
  async updateUser(request, reply) {
    try {
      const { userId } = request.params;
      const { tenantId } = request.tenant;
      const updateData = request.body;

      // 验证更新数据
      const schema = Joi.object({
        firstName: Joi.string().min(1).max(50).trim(),
        lastName: Joi.string().min(1).max(50).trim(),
        profile: Joi.object({
          avatar: Joi.string().uri(),
          bio: Joi.string().max(500),
          phone: Joi.string().pattern(/^\+?[1-9]\d{1,14}$/),
          timezone: Joi.string(),
          language: Joi.string()
        }),
        preferences: Joi.object({
          theme: Joi.string().valid('light', 'dark', 'auto'),
          notifications: Joi.object({
            email: Joi.boolean(),
            push: Joi.boolean(),
            sms: Joi.boolean()
          })
        })
      });

      const validatedData = validateData(schema, updateData);

      // 检查用户是否存在
      const user = await User.findOne({ _id: userId, tenantId });
      if (!user) {
        return reply.code(404).send(errorResponse('User not found'));
      }

      // 检查权限 (用户只能更新自己的信息，除非是管理员)
      if (request.user.id !== userId && !['admin', 'owner'].includes(request.user.role)) {
        return reply.code(403).send(errorResponse('Access denied'));
      }

      // 更新用户
      const updatedUser = await User.findByIdAndUpdate(
        userId,
        { 
          ...validatedData,
          updatedAt: new Date()
        },
        { 
          new: true, 
          runValidators: true 
        }
      ).select('-password -resetPasswordToken -emailVerificationToken');

      return reply.send(successResponse(updatedUser, 'User updated successfully'));
    } catch (error) {
      request.log.error('Error updating user:', error);
      return reply.code(500).send(errorResponse('Failed to update user', { message: error.message }));
    }
  }

  /**
   * 更新用户角色
   */
  async updateUserRole(request, reply) {
    try {
      const { userId } = request.params;
      const { role } = request.body;
      const { tenantId } = request.tenant;

      // 验证角色
      const schema = Joi.object({
        role: Joi.string().valid('user', 'admin').required()
      });

      validateData(schema, { role });

      // 检查用户是否存在
      const user = await User.findOne({ _id: userId, tenantId });
      if (!user) {
        return reply.code(404).send(errorResponse('User not found'));
      }

      // 不能修改owner的角色
      if (user.role === 'owner') {
        return reply.code(403).send(errorResponse('Cannot modify owner role'));
      }

      // 不能自己修改自己的角色
      if (request.user.id === userId) {
        return reply.code(403).send(errorResponse('Cannot modify your own role'));
      }

      // 更新角色
      user.role = role;
      user.updatedAt = new Date();
      await user.save();

      return reply.send(successResponse({
        _id: user._id,
        email: user.email,
        role: user.role,
        updatedAt: user.updatedAt
      }, 'User role updated successfully'));
    } catch (error) {
      request.log.error('Error updating user role:', error);
      return reply.code(500).send(errorResponse('Failed to update user role', { message: error.message }));
    }
  }

  /**
   * 更新用户状态
   */
  async updateUserStatus(request, reply) {
    try {
      const { userId } = request.params;
      const { status, reason } = request.body;
      const { tenantId } = request.tenant;

      // 验证状态
      const schema = Joi.object({
        status: Joi.string().valid('active', 'inactive', 'suspended').required(),
        reason: Joi.string().max(200)
      });

      validateData(schema, { status, reason });

      // 检查用户是否存在
      const user = await User.findOne({ _id: userId, tenantId });
      if (!user) {
        return reply.code(404).send(errorResponse('User not found'));
      }

      // 不能修改owner的状态
      if (user.role === 'owner') {
        return reply.code(403).send(errorResponse('Cannot modify owner status'));
      }

      // 不能自己修改自己的状态
      if (request.user.id === userId) {
        return reply.code(403).send(errorResponse('Cannot modify your own status'));
      }

      // 更新状态
      user.status = status;
      user.updatedAt = new Date();
      
      if (reason) {
        user.statusReason = reason;
      }

      await user.save();

      return reply.send(successResponse({
        _id: user._id,
        email: user.email,
        status: user.status,
        updatedAt: user.updatedAt
      }, 'User status updated successfully'));
    } catch (error) {
      request.log.error('Error updating user status:', error);
      return reply.code(500).send(errorResponse('Failed to update user status', { message: error.message }));
    }
  }

  /**
   * 删除用户
   */
  async deleteUser(request, reply) {
    try {
      const { userId } = request.params;
      const { tenantId } = request.tenant;

      // 检查用户是否存在
      const user = await User.findOne({ _id: userId, tenantId });
      if (!user) {
        return reply.code(404).send(errorResponse('User not found'));
      }

      // 不能删除owner
      if (user.role === 'owner') {
        return reply.code(403).send(errorResponse('Cannot delete owner'));
      }

      // 不能删除自己
      if (request.user.id === userId) {
        return reply.code(403).send(errorResponse('Cannot delete yourself'));
      }

      // 删除用户
      await User.findByIdAndDelete(userId);

      return reply.send(successResponse(null, 'User deleted successfully'));
    } catch (error) {
      request.log.error('Error deleting user:', error);
      return reply.code(500).send(errorResponse('Failed to delete user', { message: error.message }));
    }
  }

  /**
   * 邀请用户
   */
  async inviteUser(request, reply) {
    try {
      const { email, role, firstName, lastName, message } = request.body;
      const { tenantId } = request.tenant;

      // 验证邀请数据
      const schema = Joi.object({
        email: commonSchemas.email,
        role: Joi.string().valid('user', 'admin').required(),
        firstName: Joi.string().min(1).max(50).trim(),
        lastName: Joi.string().min(1).max(50).trim(),
        message: Joi.string().max(500)
      });

      validateData(schema, { email, role, firstName, lastName, message });

      // 检查用户是否已存在
      const existingUser = await User.findOne({ email, tenantId });
      if (existingUser) {
        return reply.code(409).send(errorResponse('User already exists in this tenant'));
      }

      // 生成邀请码和令牌
      const inviteCode = generateInviteCode();
      const inviteToken = generateToken();
      const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7天后过期

      // 创建邀请记录 (这里简化处理，实际应该有专门的Invite模型)
      const inviteData = {
        inviteId: inviteCode,
        email,
        role,
        firstName,
        lastName,
        message,
        tenantId,
        invitedBy: request.user.id,
        token: inviteToken,
        expiresAt,
        status: 'pending'
      };

      // 这里应该发送邀请邮件
      // await emailService.sendInviteEmail(inviteData);

      return reply.code(201).send(successResponse({
        inviteId: inviteCode,
        email,
        role,
        expiresAt
      }, 'User invited successfully'));
    } catch (error) {
      request.log.error('Error inviting user:', error);
      return reply.code(500).send(errorResponse('Failed to invite user', { message: error.message }));
    }
  }

  /**
   * 获取用户活动日志
   */
  async getUserActivities(request, reply) {
    try {
      const { userId } = request.params;
      const { tenantId } = request.tenant;
      const { 
        page = 1, 
        limit = 20, 
        type,
        startDate,
        endDate
      } = request.query;

      // 检查用户是否存在
      const user = await User.findOne({ _id: userId, tenantId });
      if (!user) {
        return reply.code(404).send(errorResponse('User not found'));
      }

      // 检查权限
      if (request.user.id !== userId && !['admin', 'owner'].includes(request.user.role)) {
        return reply.code(403).send(errorResponse('Access denied'));
      }

      // 构建查询条件 (这里简化处理，实际应该有专门的ActivityLog模型)
      const query = { userId, tenantId };
      
      if (type) {
        query.type = type;
      }
      
      if (startDate || endDate) {
        query.createdAt = {};
        if (startDate) {
          query.createdAt.$gte = new Date(startDate);
        }
        if (endDate) {
          query.createdAt.$lte = new Date(endDate);
        }
      }

      // 模拟活动日志数据
      const activities = [
        {
          _id: '507f1f77bcf86cd799439011',
          type: 'login',
          description: 'User logged in',
          metadata: { method: 'email' },
          ipAddress: request.ip,
          userAgent: request.headers['user-agent'],
          createdAt: new Date()
        }
      ];

      const total = activities.length;

      return reply.send(paginatedResponse(activities, total, page, limit, 'User activities retrieved successfully'));
    } catch (error) {
      request.log.error('Error getting user activities:', error);
      return reply.code(500).send(errorResponse('Failed to get user activities', { message: error.message }));
    }
  }
}

module.exports = new UserController();